<template>
    <div class="wrap-table fllow-manage">
        <el-form ref="form" :model="searchData" label-width="100px" class="clearfix flex-div">
            <el-form-item label="上课日期"  label-width="70px" class="" style="width: 350px">
                <div class="block">
                    <el-date-picker
                            v-model="timeDate"
                            type="daterange"
                            align="right"
                            unlink-panels
                            range-separator="至"
                            value-format="yyyy-MM-dd"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            :picker-options="pickerOptions">
                    </el-date-picker>
                </div>
            </el-form-item>
            <el-form-item label="预产期"  label-width="70px" class="" style="width: 350px">
                <div class="block">
                    <el-date-picker
                            v-model="uisDate"
                            type="daterange"
                            align="right"
                            unlink-panels
                            range-separator="至"
                            value-format="yyyy-MM-dd"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            :picker-options="pickoption2">
                    </el-date-picker>
                </div>
            </el-form-item>
            <el-form-item label="事项标题(课程名称)" class="" label-width="150px" style="width: 260px">
                <el-input v-model="searchData.scheduleName" style="width: 100px;"></el-input>
            </el-form-item>
            <!--<transition name="fade">-->
                <!--<div class="moreSearch" v-show="showActive">-->
            <el-form-item label="所在地区" label-width="80px" class=" item-right" style="width:200px">
                <el-select v-model="searchData.districtNo" placeholder="请选择"  clearable :disabled="JSON.parse(UserDic).IsCommunityOnly=='1'">
                    <el-option
                            v-for="item in optionDiq"
                            :key="item.DistrictName"
                            :label="item.DistrictName"
                            :value="item.DistrictNo">
                    </el-option>
                </el-select>
            </el-form-item>
                    <el-form-item label="预约状态" class="" style="width: 200px">
                        <el-select v-model="searchData.appointState" clearable placeholder="请选择">
                            <el-option
                                    v-for="item in options1"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="事项状态" class=""  style="width: 200px">
                        <el-select v-model="searchData.completeState" clearable placeholder="请选择">
                            <el-option
                                    v-for="item in options2"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="上课时研究阶段" label-width="120px" class="" style="width:220px">
                        <el-select v-model="searchData.period" clearable placeholder="请选择">
                            <el-option
                                    v-for="item in options2sp"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="试验类型" class=" item-right" style="width:260px">
                        <el-select v-model="searchData.testType" clearable placeholder="请选择">
                            <el-option
                                    v-for="item in options6"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item class=" item-right" style="width:260px;margin-left: -60px" label="">
                        <el-input v-model="searchData.keyword" placeholder="研究对象手机号"></el-input>
                    </el-form-item>
                <!--</div>-->
            <!--</transition>-->
            <div class="flex-r-but">
                <el-button type="success" @click="outPut" class="  mg-lr-20 pd-bt">导出</el-button>
                <el-button type="primary" @click="checkList" class=" mg-lr-20 pd-bt">查询</el-button>
            </div>

            <!--<el-button class="pull-right" @click="showActive=!showActive"><span v-if="!showActive">更多</span><span v-else>收起</span></el-button>-->
        </el-form>
        <!---->
        <template>
            <el-table
                    :data="tableData"
                    border
                    id="out-table"
                    v-loading="loading"
                    element-loading-text="加载中"
                    style="width: 100%">
                <el-table-column align="center" label="序号" width="70">
                    <template  slot-scope="scope">
                        {{scope.$index+1}}
                    </template>
                </el-table-column>
                <el-table-column
                        prop="LessonDate"
                        align="center"
                        label="上课日期"
                        min-width="160">
                    <template  slot-scope="scope">
                        <span class="excelHidden">{{scope.row.LessonDate}}</span>
                        <el-date-picker
                                v-model="scope.row.LessonDate"
                                :clearable="false"
                                 :disabled="true"
                                @change="changeFollowUpDate(scope.row,scope.row.LessonDate)"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="选择日期">
                        </el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="LessonTime"
                        label="上课时间"
                        align="center"
                        min-width="120">
                    <template  slot-scope="scope">
                        <span class="excelHidden">{{scope.row.LessonTime}}</span>
                        <el-time-select
                                v-model="scope.row.LessonTime"
                                :clearable="false"
                                @change="changeFollowUpDateOne(scope.row,scope.row.LessonTime)"
                                :picker-options="{start: '08:00', step: '00:15',end: '21:30'}"
                                placeholder="">
                        </el-time-select>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="ExpectedDate"
                        label="预产期"
                        align="center"
                        :show-overflow-tooltip="true"
                        min-width="120"
                        >
                </el-table-column>
                <el-table-column
                        prop="LessonName"
                        label="事项标题"
                        :show-overflow-tooltip="true"
                        align="center"
                        min-width="180">
                </el-table-column>
                <el-table-column
                        prop="AppointState"
                        label="预约状态"
                        align="center"
                        :formatter="AppointFilter"
                        min-width="120">
                    <template  slot-scope="scope">
                        <span class="excelHidden" style="color:#f00">({{scope.row.AppointState |AppointState}})</span>
                        <el-select v-model="scope.row.AppointState" placeholder="请选择" @change="changeFollowUpDate(scope.row,scope.row.AppointState)">
                            <el-option
                                    v-for="item in options1s"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="CompleteState"
                        label="事项状态"
                        :formatter="FollowUpFilter"
                        align="center"
                        min-width="120">
                    <template  slot-scope="scope">
                        <span class="excelHidden">({{scope.row.CompleteState |CompleteState}})</span>
                        <el-select v-model="scope.row.CompleteState" placeholder="请选择" @change="changeCompleteState(scope.row,scope.row.CompleteState)">
                            <el-option
                                    v-for="item in options3s"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="Surname"
                        label="姓名首字母"
                        align="center"
                        min-width="100">
                </el-table-column>
                <el-table-column
                        label="手机号"
                        align="center"
                        min-width="120">
                    <template slot-scope="scope">
                        <el-tooltip :content="scope.row.Mobile" placement="top">
                            <span class="" @click="JumpUserinfo(scope.row)">{{scope.row.Mobile}}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="Period"
                        label="上课时研究阶段"
                        :formatter="PeriodFilter"
                        align="center"
                        min-width="140">
                </el-table-column>
                <el-table-column
                        prop="IntensityOfIntervention"
                        label="上课时干预强度"
                        :formatter="IntensityFilter"
                        align="center"
                        min-width="140">
                </el-table-column>
                <el-table-column
                        label="陪同人员"
                        align="center"
                        min-width="160">
                        <template slot-scope="scope">
                            <span @click="showDialog(scope.row)"
                                  style="cursor: pointer;color: #2DA3FB">{{scope.row.AccompanyPerson }}<i class="el-icon-edit"></i></span>
                        </template>
                </el-table-column>
                <el-table-column
                        prop="Remark"
                        label="事项备注"
                        align="center"
                        min-width="160">
                    <template slot-scope="scope">
                        <span class="excelHidden">{{scope.row.Remark ||'-'}}</span>
                        <el-input @blur="changeFollowUpDate(scope.row,scope.row.Remark)" v-model="scope.row.Remark" placeholder="事项备注"></el-input>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="CancleReason"
                        label="事项取消原因"
                        align="center"
                        min-width="160">
                    <template slot-scope="scope">
                        <span class="excelHidden">{{scope.row.CancleReason ||'-'}}</span>
                        <el-input @blur="changeFollowUpDate(scope.row,scope.row.CancleReason)" v-model="scope.row.CancleReason" placeholder="事项取消原因"></el-input>
                    </template>
                </el-table-column>
            </el-table>
        </template>
        <el-dialog title="陪同人员" :visible.sync="dialogFos" top="5vh" width="30%" :close-on-click-modal="false">
                <el-checkbox-group v-model="Companions" @change="changeCops">
                    <el-checkbox label="丈夫/伴侣" style="display: block;margin:10px"></el-checkbox>
                    <el-checkbox label="母亲" style="display: block;margin:10px"></el-checkbox>
                    <el-checkbox label="婆婆/孩子" style="display: block;margin:10px"></el-checkbox>
                    <el-checkbox label="父亲" style="display: block;margin:10px"></el-checkbox>
                    <el-checkbox label="公公" style="display: block;margin:10px"></el-checkbox>
                    <el-checkbox label="其他" style="display: block;margin:10px"></el-checkbox>
                </el-checkbox-group>
                <el-input v-if="Companions.indexOf('其他')>-1" v-model="CompanionsOther"  placeholder="请输入内容"></el-input>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFos = false">取 消</el-button>
                <el-button type="primary" @click="saveCompai">确认</el-button>
            </div>
        </el-dialog>
        <!--分页-->
        <div class="block mg-20-auto pagination-fixed">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="pageId"
                    :page-sizes="[10, 20, 30, 40,80,100,200,500]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
    </div>
</template>
<script>
import {mapGetters} from 'vuex'
import {DIC_PERIODA,filterPeriod} from '@/utils/localDic'
import FileSaver from 'file-saver'   //导出
import XLSX from 'xlsx'
export default {
    data() {
        return {
            searchData:{
                sysId:'',
                appointState:'',
                completeState:'',
                userState:'',
                groupType:'',
                keyword:'',
                period:'',
                scheduleName: '',
                districtNo:'',
                testType:'2'
            },
	        Companions:[],
            timeDate:[],
	        dialogFos:false,
            optionDiq:[],
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                            onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                            onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }],
            },
            pickoption2: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', [start, end]);
                }
                }, {
                    text: '最近一个月',
                            onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                            onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }],
            },
            pageId:1,
            total:null,
            loading:true,
            pageSize:10,
            tableData:[],
            options1:  [{value: '', label: '全部'},{value: '0', label: '待确认'},{value: '1', label: '已确认'}, {value: '2', label: '已取消'}],
            options1s: [{value: '0', label: '待确认'},{value: '1', label: '已确认'}, {value: '2', label: '已取消'}],
            options2: [{value: '', label: '全部'}, {value: '0', label: '待完成'},{value: '1', label: '已完成'}, {value: '2', label: '已取消'}, {value: '3', label: '爽约'}],
            options3s: [ {value: '0', label: '待完成'},{value: '1', label: '已完成'}, {value: '2', label: '已取消'}, {value: '3', label: '爽约'}],
            optionss6: [{value: '', label: '全部'},{value: '1', label: 'A'}, {value: '2', label: 'B'}],
            options6: [{value: '', label: '全部'},{value: '0', label: '预试验'},{value: '1', label: '正式试验'},{value: '2', label: '预试验+正式试验'}],
            options2sp:DIC_PERIODA,
            optionsSubjectNames: [
                {value: '0', label: '孕期营养必修课'},
                {value: '1', label: '一起来运动吧'},
                {value: '2', label: '烹饪课'},
                {value: '3', label: '月子里怎么吃才好'},
                {value: '4', label: '母乳喂养妈妈会'},
            ],
            PeriodFilter(row, column, cellValue, index){
                return filterPeriod(cellValue)
            },
            IntensityFilter(row, column, cellValue, index){
                return cellValue==1?'AA':'A'
            },
            AppointFilter(row, column, cellValue, index){
                return cellValue==1?'已预约':(cellValue==0?'待确认':'已取消')
            },
            FollowUpFilter(row, column, cellValue, index){
                return cellValue==1?'已完成':'待完成'
            },
            FollowUpTypeFilter(row, column, cellValue, index){
                switch(cellValue){
                    case '0':
                        return '孕期营养必修课';
                        break;
                    case '1':
                        return '一起来运动吧';
                        break;
                    case '2':
                        return '烹饪课';
                        break;
                    case '3':
                        return '月子里怎么吃才好';
                        break;
                    case '4':
                        return '母乳喂养妈妈会'
                }
            },
            maxHeight:'',
            ResearchObjectId:'',
            ScheduleId:'',
            showActive:false,
            pageSizeQ:5,
            tablerow:null,
            copyObject:null,
            onOFFsub:false,
            optionsNurse:[],
            uisDate:[],
            dialogRow:'',
	        CompanionsOther:''
        }
    },
    filters:{
        IsFillInQuestionFilter(cellValue){
            if(cellValue==1){
                return '已完成'
            }
            else if(cellValue==0){
                return '未完成'
            }
            else{
                return '-'
            }
        },
        mobileFilter(cellValue) {
            return cellValue.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
        },
        AppointState(cellValue) {
            return cellValue==1?'已预约':(cellValue==0?'待确认':'已取消')
        },
        CompleteState(cellValue)
        {
            if (cellValue == 0) {
                return '待完成'
            }
            else if (cellValue == 1) {
                return '已完成'
            }
            else if (cellValue == 2) {
                return '已取消'
            }
            else {
                return '爽约'
            }
        }
    },
    created() {

    },
    computed:{
        ...mapGetters([
                'userIcon',
                'userId',
                'token',
	            'UserDic'
            ]),
    },
    async mounted(){
        let that=this;
        let now = new Date();
        let nowTime = now.getTime() ;
        let day = now.getDay();
        let oneDayLong = 24*60*60*1000 ;
        if(day==0){     //西方从周日算为第一天    2018/10/28
            day=7
        }
        let MondayTime = nowTime - (day-1)*oneDayLong  ;
        let SundayTime =  nowTime + (7-day)*oneDayLong ;
        let monday = dateForm(new Date(MondayTime));
        let sunday = dateForm(new Date(SundayTime));
        that.timeDate= [
            monday,
            sunday
        ];   //初始化时间范围
        JSON.parse(localStorage.getItem('healthManage1'))?that.searchData=JSON.parse(localStorage.getItem('healthManage1')):''
	    await that.GetCommunityDistrict()
	    that.searchData.districtNo=JSON.parse(that.UserDic).DistrictNo||that.searchData.districtNo||''
        that.getList()
    },
    beforeMount:function() {
        let that=this;
        let appHeight=$(window).height();
        let autoheight=(appHeight-288)+'px'
        that.maxHeight=autoheight

    },
    watch:{
        'dialogRow.AccompanyPerson':{
        	handler(val){
        		console.log(val)
            },
            deep:true
        }
    },
    methods: {
	    showDialog(row){
	    	this.dialogFos=true
            this.Companions=[]
            this.dialogRow=JSON.parse(JSON.stringify(row))
		    this.Companions=(row.AccompanyPerson||'').split(',')
		    this.Companions=this.Companions.filter(val=>{
		    	return val=='丈夫/伴侣'||val=='母亲'||val=='父亲'||val=='公公'||val=='婆婆/孩子'||val=='其他'
            })
            if((row.AccompanyPerson||'').indexOf('其他')>-1){
	            this.CompanionsOther=(row.AccompanyPerson||'').replace('丈夫/伴侣','').replace('母亲','').replace('父亲','').replace('公公','').replace('婆婆/孩子','').replace('其他','').replace(/\,/g,'')
            }
        },
	    changeCops(val){  //多选框
		     this.dialogRow.AccompanyPerson =val.join(',')
	    },
	    saveCompai(){
            let onOff=false
		    let newArr=this.dialogRow.AccompanyPerson.split(',').filter(val=>{
		    	if(val=='其他'){
				    onOff=true
                }
		    	return val!=''
            })
		    this.dialogRow.AccompanyPerson=newArr.join(',')
		    onOff? this.dialogRow.AccompanyPerson+=','+this.CompanionsOther:''
		    this.setList(this.dialogRow)
		    this.CompanionsOther=''
            this.dialogFos=false
        },
        async GetCommunityDistrict(){    //获取社区行政区
            let that = this;
            await that.service({
                url: "/Dic/GetCommunityDistrict",
                method: "get",
                params: {
                }
            }).then(response => {
                that.optionDiq=response.dtData;
            })
            .catch(data => {
	           console.log(data)
            });
        },
        outPut:function(){  //导出
            /* generate workbook object from table */
            var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
            /* get binary string as output */
            var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array',width:'300'})
            try {
                FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '健教管理.xlsx')
            } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
            return wbout
        },
        changeFollowUpDate:function(row,val){
            this.setList(row)
        },
        changeCompleteState:function(row,val){  //事项完成状态
            let that=this;
            if(val=='1'){          //如果改成已完成
                that.$confirm('健康教育课状态改成已完成将会生成满意度调查记录 , 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    that.setList(row)
                }).catch(() => {
                    that.getList()
                });
            }
            else{
                that.setList(row)
            }
        },
        checkList:function(){   //查询
            this.pageId=1;
            this.pageSize=10;
            this.total=null;
            this.getList()
            let storageObj=this.searchData
            localStorage.setItem('healthManage1',JSON.stringify(storageObj))
        },
        changeFollowUpDateOne:function(row,val){
            let that=this;
            if(row.AppointState==0){
                this.$confirm('是否将预约状态改为已确认 , 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                   row.AppointState='1';
                   that.setList(row)
                }).catch(() => {
                    that.setList(row)
                });
            }
            else{
                 that.setList(row)
            }
        },
        jumpQuestion:function(row){   //问卷跳转
            let that=this;
            if(row.IsFillInQuestionnaire==undefined){
                return false
            }
            that.$router.push({
                path:'/participant/editor',
                query:{
                    id:row.ResearchObjectId,
                    mobile:row.Mobile,
                    researchNo:row.ResearchNo,
                    isOther:1
                }
            })
        },
        jumpMove:function(row){  //跳转行动计划
            let that=this;
            that.$router.push({
                path:'/participant/editor',
                query:{
                    id:row.ResearchObjectId,
                    mobile:row.Mobile,
                    researchNo:row.ResearchNo,
                    isOther:2
                }
            })

        },
        JumpUserinfo:function(row){   //跳转用户基本信息
            let that=this;
        },
        handleSizeChange(val) {       //条数改变
            this.pageSize=val;
            this.getList()
        },
        handleCurrentChange(val) {    //页数改变
            this.pageId = val
            this.getList()
        },
        handleSizeChangeQ(val) {       //条数改变
            this.pageSizeQ=val;
            this.getListQ()
        },
        handleCurrentChangeQ(val) {    //页数改变
            this.pageIdQ = val
            this.getListQ()
        },
        setList:function(row){  //修改
            let that=this;
            row.CancleReason = row.CompleteState != 2 ? '' : row.CancleReason
            that.service({
                url:'/ResearchObject/SaveLesson',
                method:'post',
                data:{
                        ...row
                }
                }).then(response=>{
                        that.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    that.getList()
                }).catch(data=>{
                    that.getList()
            })
        },
        getList:function(){           //获取一级信息列表
            let that=this
            that.loading=true
            that.service({
                url:'/ResearchObject/GetLesson',
                method:'get',
                params:{
                    pageCount:(that.pageId-1),
                    pageSize:that.pageSize,
                        ...that.searchData,
                    startDate:that.timeDate?that.timeDate[0]:'',
                    endDate:that.timeDate?that.timeDate[1]:'',
                    startPreDate:that.uisDate?(that.uisDate[0] ||''):'',
                    endPreDate:that.uisDate?(that.uisDate[1] ||''):'',
                }
                }).then(response=>{
                    that.tableData=response.dtData;
                    that.total =parseInt(response.dtData[0].TotalCount);
                    that.loading=false
                }).catch(data=>{
                that.loading=false
            })
        },
    }
  }
function addZero(s){
    return s < 10 ? '0' + s: s;
}
function dateForm(data){
    return   new Date(data).getFullYear()+'-'+addZero((new Date(data).getMonth()+1))+'-'+addZero(new Date(data).getDate())
}
</script>
<style scoped lang="scss">
    .formX{
    .top{
        text-align: center;
    }
    ul{
    li{
        margin:20px;
    h3{
        color: #606266;
        font-weight: normal;
    }
    h5{
        font-weight: normal;
        margin:5px 0;
    }
    p{
        color: #999999;
        margin-bottom: 10px;
        margin:10px 0px;
    }
    }
    }
    }
    .click_line{cursor: pointer;color:#409EFF;}
    .fade-enter-active, .fade-leave-active {
        transition: opacity .4s;
    }
    .fade-enter, .fade-leave-to{
        opacity: 0;
    }
    .pagination-fixed{
     position: static;
    }
    .excelHidden{display: none !important;}
</style>
